<template>
  <div class="controls">
    <div class="slider-player-wrap" id="playerSliderWrap">
      <div class="slider-player" id="sliderPlayer">
        <input
          id="playerSlider"
          type="text"
          data-slider-tooltip="hide"
          data-slider-value="0"
          data-slider-min="0"
          data-slider-max="100"
        />
      </div>
      <span class="slider-tooltip" id="sliderTooltip">
        <div class="slider-tooltip-arrow"></div>
        <div class="slider-tooltip-inner">00:00</div>
      </span>
    </div>

    <div class="controls-wrap">
      <div class="controls-left">
        <div id="playButton" class="play-btn-wrap">
          <span id="playButtonIcon" class="play-btn" title="播放"></span>
        </div>
        <div class="play-time-wrap">
          <span id="palyTimeCurrent" class="paly-time-current">00:00:00</span>
          <span class="play-time-separator">/</span>
          <span id="playTimeDuration" class="play-time-duration">00:00:00</span>
        </div>

        <div class="slider-voice-wrap">
          <span id="voiceButton" class="slider-voice-icon"></span>
          <div class="slider-voice">
            <input
              id="voiceSlider"
              type="text"
              data-slider-tooltip="hide"
              data-slider-value="1"
              data-slider-step="0.1"
              data-slider-min="0"
              data-slider-max="1"
            />
          </div>
        </div>
      </div>
      <div class="controls-right">
        <ul class="controls-group">
          <li class="item">
            <div class="quit-btn-wrap" id="quitButton">
              <span class="quit-btn" title="退出登录"></span>
            </div>
          </li>
          <li class="item" id="bulletsScreen" style="display: none">
            <div class="bullets-screen-btn-wrap">
              <span class="bullets-screen-btn" title="关闭弹幕"></span>
            </div>
          </li>
          <li class="item">
            <div class="thumbnail-list-btn-wrap" id="thumbnailListButton" style="display: none">
              <span class="thumbnail-list-btn" title="文档列表"></span>
            </div>
          </li>
          <li class="item">
            <div class="play-rate-wrap" id="playRateWrap">
              <span class="play-rate-btn" id="playRateBtn" title="设置倍速播放">正常</span>
              <ul class="play-rate-list" id="playRateList">
                <li class="play-rate-number">2.0X</li>
                <li class="play-rate-number">1.5X</li>
                <li class="play-rate-number">1.25X</li>
                <li class="play-rate-number active">正常</li>
                <li class="play-rate-number">0.8X</li>
              </ul>
            </div>
          </li>
          <li class="item">
            <div class="switch-btn-wrap" id="switchBtnWrap">
              <span class="switch-btn" title="切换窗口"></span>
            </div>
          </li>
          <li class="item">
            <div class="full-screen-btn-wrap" id="fullScreenButtonWrap">
              <span class="full-screen-btn" title="网页全屏"></span>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import Component from '@views/live/cc/common/component'
import Render from '@views/live/cc/common/render' //公共方法
import Utils from '@views/live/cc/common/utils'
import FullScreen from './fullscreen'
import LoadBar from './loadbar'
import Slider from 'bootstrap-slider'
import 'bootstrap-slider/dist/css/bootstrap-slider.css'
export default {
  data() {
    return {
      timer: 0,
      interval: 999,
      delaySeek: 0,
      isPlayerLoad: false,
      playState: false,
      durationTime: 0,
      currentTime: 0,
      formatCurrentTime: 0,
      isShowThumbnailList: false,
      isShowRate: false,
      isMute: false,
      volume: 0,
      isPlayerSliderAutoChange: true,
      isVideoMain: true,
      isH5play: false,
      isFullScreen: false,
      isSwitch: true,
      HDScene: null,
      loadBar: null,
      ui: null,
      component: null,
      render: null,
      fullScreen: null,
      playButton: null,
      bulletsScreen: null,
      playButtonIcon: null,
      playTimeDuration: null,
      palyTimeCurrent: null,
      voiceButton: null,
      quitButton: null,
      switchBtnWrap: null,
      thumbnailWrapper: null,
      playRateWrap: null,
      playRateList: null,
      playRateBtn: null,
      playRateNumber: null,
      playerSlider: null,
      voiceSlider: null
    }
  },
  methods: {
    init() {
      this.HDScene = window.replayHDScene
      this.render = new Render()
      this.component = new Component()
      this.fullScreen = new FullScreen()
      this.playButton = this.render.getNode('playButton')
      this.bulletsScreen = this.render.getNode('bulletsScreen')
      this.playButtonIcon = this.render.getNode('playButtonIcon')
      this.playTimeDuration = this.render.getNode('playTimeDuration')
      this.palyTimeCurrent = this.render.getNode('palyTimeCurrent')
      this.voiceButton = this.render.getNode('voiceButton')
      this.quitButton = this.render.getNode('quitButton')
      this.switchBtnWrap = this.render.getNode('switchBtnWrap')
      this.thumbnailListButton = this.render.getNode('thumbnailListButton')
      this.thumbnailWrapper = this.render.getNode('thumbnailWrapper')
      this.playRateWrap = this.render.getNode('playRateWrap')
      this.playRateList = this.render.getNode('playRateList')
      this.playRateBtn = this.render.getNode('playRateBtn')
      this.playRateNumber = [...document.getElementsByClassName('play-rate-number')]

      this.onEvents()
      this.initSlider()
      this.handleClick()
    },
    onEvents() {
      this.HDScene.onDocumentMode(data => {
        if (!data.fastMode && this.fullScreen.isSupportFullscreen) {
          this.isSwitch = false
        }
      })
      this.HDScene.onPlayerMode(data => {
        this.isH5play = data.isH5play
        this.autoPlay(this.isH5play)
        if (!this.isH5play && this.fullScreen.isSupportFullscreen) {
          this.isSwitch = false
        }
        if (!this.isH5play) {
          this.playRateWrap.parentNode.style.display = 'none'
        }
      })
      this.HDScene.onPlayerLoad(() => {
        this.isPlayerLoad = true
        this.updateVolume()
        this.setDurationTime()
        this.updateCurrentTime()
        this.HDScene.emit('initLoadBar', this.durationTime)
        this.HDScene.emit('isPlayerLoad', this.isPlayerLoad)
        Utils.log('onPlayerLoad', this.isPlayerLoad)
        this.autoPlay(this.isH5play)
      })
      this.HDScene.onPlayerStart(() => {
        this.playState = true
        this.onPlayStateChange(this.playState)
        Utils.log('onPlayerStart', this.playState)
      })
      this.HDScene.onPlayerPause(() => {
        this.playState = false
        this.onPlayStateChange(this.playState)
        Utils.log('onPlayerPause', this.playState)
      })
      this.HDScene.onPlayerResume(() => {
        this.playState = true
        this.onPlayStateChange(this.playState)
        Utils.log('onPlayerResume', this.playState)
      })
      this.HDScene.onPlayerEnd(() => {
        this.playState = false
        this.updateCurrentTime()
        this.onPlayStateChange(this.playState)
        Utils.log('onPlayerEnd', this.playState)
      })
      this.HDScene.onBarrageInfo(data => {
        Utils.log('barrage', data)
        this.bulletsScreen.style.display = data.isBarrage == 1 ? 'blcok' : 'none'
      })
    },

    initSlider() {
      this.playerSlider = new Slider('#playerSlider', {})
      this.HDScene.once('initLoadBar', durationTime => {
        this.loadBar = new LoadBar({
          element: 'playerSliderWrap',
          durationTime: durationTime
        })
      })
      this.playerSlider.on('slideStop', value => {
        this.onSeek(value)
      })
      this.playerSlider.on('change', value => {
        if (value.newValue == 0) {
          this.loadBar && this.loadBar.loadBarRegress()
        } else {
          this.loadBar && this.loadBar.loadBarGrayToOrange()
        }
      })
      let playerSliderWrap = document.getElementById('playerSliderWrap')
      playerSliderWrap.onclick = event => {
        if (event.target.id == 'playerSliderWrap') {
          this.onSeek(0)
        }
      }

      this.voiceSlider = new Slider('#voiceSlider', {})
      this.voiceSlider.on('slideStop', value => {
        this.setVolume(value)
      })
    },

    handleClick() {
      let leftBar = this.render.getNode('leftBar')
      let rightBar = this.render.getNode('rightBar')
      let fullScreenButtonWrap = this.render.getNode('fullScreenButtonWrap')

      this.component.bind(leftBar, 'click', this.bindLeftBar.bind(this))
      this.component.bind(rightBar, 'click', this.bindRightBar.bind(this))
      this.component.bind(fullScreenButtonWrap, 'click', this.bindFullScreen.bind(this))

      this.component.bind(this.switchBtnWrap, 'click', this.bindSwitchBtnWrap.bind(this))
      this.component.bind(this.playButton, 'click', this.bindPlay.bind(this))
      this.component.bind(this.voiceButton, 'click', this.toggleMute.bind(this))
      this.component.bind(this.quitButton, 'click', this.bindQuit.bind(this))
      this.component.bind(this.playRateWrap, 'click', this.bindPlayRateWrap.bind(this))
      this.component.bind(this.playRateList, 'click', this.bindPlayRateList.bind(this))
      this.component.bind(this.thumbnailListButton, 'click', this.toggleThumbnailList.bind(this))
    },

    autoPlay(isH5play) {
      if (!isH5play) {
        this.bindSwitchBtnWrap()
      }
    },

    bindFullScreen() {
      this.fullScreen.toggleFullScreen({
        fullScreenStateChange: data => {
          this.isFullScreen = data.isFullScreen
          this.fullScreenChangeCallback(data)
        }
      })
    },

    fullScreenChangeCallback(data) {
      if (typeof data.isFullScreen == 'undefined') {
        return false
      }
      this.loadBar && this.loadBar.initTooltip && this.loadBar.initTooltip()
      if (data.isFullScreen) {
        this.quitButton.style.display = 'none'
        !this.isSwitch && (this.switchBtnWrap.parentNode.style.display = 'none')
      } else {
        this.quitButton.style.display = 'block'
        !this.isSwitch && (this.switchBtnWrap.parentNode.style.display = 'block')
      }
    },

    bindLeftBar() {
      this.fullScreen.toggleLeftBar({
        barStateChange: data => {
          this.loadBar && this.loadBar.initTooltip && this.loadBar.initTooltip()
        },
        fullScreenStateChange: data => {
          this.fullScreenChangeCallback(data)
        }
      })
    },

    bindRightBar() {
      this.fullScreen.toggleRightBar({
        barStateChange: data => {
          this.loadBar && this.loadBar.initTooltip && this.loadBar.initTooltip()
        },
        fullScreenStateChange: data => {
          this.fullScreenChangeCallback(data)
        }
      })
    },

    bindSwitchBtnWrap() {
      if (this.isFullScreen && this.fullScreen.isSupportFullscreen) {
        this.switchNode()
      } else {
        this.switchClass()
      }
    },

    switchNode() {
      let player = this.render.getNode('player')
      let drawPanel = this.render.getNode('document')
      let playerChildren = player.firstElementChild
      let drawPanelChildren = drawPanel.firstElementChild
      player.appendChild(drawPanelChildren)
      drawPanel.appendChild(playerChildren)
    },

    switchClass() {
      let left = document.querySelector('.left')
      let center = document.querySelector('.center')
      let leftBar = document.getElementById('leftBar')
      let rightBar = document.getElementById('rightBar')
      let questionWrapper = document.querySelector('.question-wrapper')
      let controlsWrapper = document.querySelector('.controls-wrapper')
      let thumbnailWrapper = document.querySelector('.thumbnail-wrapper')
      let leftId = left.id
      let centerId = center.id
      let leftClassName = left.className
      let centerClassName = center.className
      let leftStyle = left.getAttribute('style') || ''
      let centerStyle = center.getAttribute('style') || ''

      left.id = centerId
      center.id = leftId
      left.className = centerClassName
      center.className = leftClassName
      left.setAttribute('style', centerStyle)
      center.setAttribute('style', leftStyle)

      center.appendChild(questionWrapper)
      left.insertBefore(leftBar, left.childNodes[0])
      left.appendChild(thumbnailWrapper)
      left.appendChild(controlsWrapper)
      left.appendChild(rightBar)

      this.isVideoMain = !this.isVideoMain

      this.HDScene.emit('switch', this.isVideoMain)
    },

    bindPlayRateList(e) {
      if (!this.checkout('bindPlayRateList')) {
        return false
      }
      this.playRateNumber.forEach(element => {
        this.render.removeClass(element, 'active')
      })
      let option = e.target
      this.render.addClass(option, 'active')
      let rateLabel = option.innerHTML
      let rate = rateLabel.substring(0, rateLabel.length - 1)
      this.HDScene.rate = rate
      Utils.log('rate', rate)
      this.playRateBtn.innerHTML = rateLabel
      this.interval = Math.floor(999 / rate)
      Utils.log('interval', this.interval)
      this.startTimer()
    },

    bindPlayRateWrap() {
      if (this.isShowRate) {
        this.playRateList.style.display = 'none'
        this.render.removeClass(this.playRateWrap, 'select')
      } else {
        this.playRateList.style.display = 'block'
        this.render.addClass(this.playRateWrap, 'select')
      }
      this.isShowRate = !this.isShowRate
    },

    onPlayStateChange(playState) {
      let _playState = playState
      if (_playState) {
        this.startTimer()
        this.render.addClass(this.playButtonIcon, 'pause')
        this.playButtonIcon.title = '暂停'
      } else {
        this.stopTimer()
        this.render.removeClass(this.playButtonIcon, 'pause')
        this.playButtonIcon.title = '播放'
      }
    },

    toggleThumbnailList() {
      if (this.isShowThumbnailList) {
        this.thumbnailWrapper.style.display = 'none'
        this.render.removeClass(this.thumbnailListButton.getElementsByTagName('span')[0], 'active')
      } else {
        this.render.addClass(this.thumbnailListButton.getElementsByTagName('span')[0], 'active')
        this.thumbnailWrapper.style.display = 'block'
        this.HDScene.emit('showThumbnailList')
      }
      this.isShowThumbnailList = !this.isShowThumbnailList
    },

    bindQuit() {
      this.$messageBox
        .confirm('您确定要退出吗？', {
          title: '退出'
        })
        .then(() => {
          this.HDScene.logout()
          this.$router.go(-1)
        })
        .catch(() => {})
    },

    bindPlay() {
      if (!this.checkout('bindPlay')) {
        return false
      }
      this.HDScene.togglePlay()
    },

    stopTimer() {
      clearInterval(this.timer)
    },

    startTimer() {
      this.timer && this.stopTimer()
      this.timer = setInterval(this.bindTimerUpdate.bind(this), this.interval)
    },

    bindTimerUpdate() {
      this.updateCurrentTime()
    },

    setDurationTime() {
      this.durationTime = this.HDScene.durationTime
      this.playTimeDuration.innerText = Utils.formatSeconds(this.durationTime)
      this.setPlayerSliderMax()
    },

    updateCurrentTime() {
      this.currentTime = Math.ceil(this.HDScene.currentTime)
      if (this.currentTime > this.durationTime) {
        this.currentTime = this.durationTime
      }
      this.formatCurrentTime = Utils.formatSeconds(this.currentTime)
      this.palyTimeCurrent.innerText = this.formatCurrentTime
      this.updatePlayerSliderValue()
      if (this.currentTime > 0) {
        this.loadBar && this.loadBar.loadBarGrayToOrange()
      } else {
        this.loadBar && this.loadBar.loadBarRegress()
      }
    },

    updateVolume() {
      this.volume = this.HDScene.volume
      this.voiceSlider.setValue(this.volume)
      this.updateMute(this.volume)
      Utils.log('updateVolume volume', this.volume)
    },

    setVolume(volume) {
      if (!this.checkout('setVolume')) {
        return false
      }
      this.HDScene.volume = volume
      this.volume = this.HDScene.volume
      this.updateMute(this.volume)
      Utils.log('setVolume volume', this.volume)
    },

    toggleMute() {
      if (!this.checkout('toggleMute')) {
        return false
      }
      if (this.isMute) {
        if (!this.volume) {
          this.volume = 1
        }
        this.HDScene.volume = this.volume
      } else {
        this.HDScene.volume = 0
      }
      this.updateMute(this.HDScene.volume)
      this.voiceSlider.setValue(this.HDScene.volume)
      Utils.log('toggleMute volume', this.HDScene.volume)
    },

    updateMute(volume) {
      if (volume == 0) {
        this.render.addClass(this.voiceButton, 'mute')
        this.isMute = true
        Utils.log('updateMute', this.isMute)
      } else {
        this.isMute = false
        this.render.removeClass(this.voiceButton, 'mute')
        Utils.log('updateMute', this.isMute)
      }
    },

    setPlayerSliderMax() {
      this.playerSlider.setAttribute('max', this.durationTime)
    },

    onSeek(value) {
      if (!this.checkout('onSeek')) {
        return false
      }
      this.isPlayerSliderAutoChange = false
      this.delaySeek && clearTimeout(this.delaySeek)
      this.delaySeek = setTimeout(() => {
        this.stopTimer()
        this.HDScene.seek(value)
        if (Utils.IEVersion() != -1) {
          this.updateCurrentTime()
        }
        this.isPlayerSliderAutoChange = true
      }, 500)
      return true
    },

    updatePlayerSliderValue() {
      if (!this.isPlayerSliderAutoChange) {
        return false
      }
      this.playerSlider.setValue(this.currentTime)
      return true
    },

    checkout(message) {
      if (!this.isPlayerLoad) {
        Utils.log(`${message} fail await player load!`)
        return false
      }
      return true
    }
  },
  mounted() {
    this.init()
  }
}
</script>
<style lang="scss">
@import './controls.scss';
</style>
